package cn.wonderland.org.service.impl;

import cn.wonderland.base.service.impl.BaseServiceImpl;
import cn.wonderland.base.util.PageList;
import cn.wonderland.org.domain.Department;
import cn.wonderland.org.mapper.DepartmentMapper;
import cn.wonderland.org.query.DepartmentQuery;
import cn.wonderland.org.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional()
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements DepartmentService {
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public List<Department> deptTree() {

        List<Department> result = new ArrayList<>();
        // 查询出所有的数据
        List<Department> allDepartments = departmentMapper.findAll();
        // 将全部的部门数据转成map
        Map<Long, Department> deptMap = allDepartments.stream().collect(Collectors.toMap(Department::getId, department -> department));
        for (Department dept : allDepartments) {
            if (dept.getParentId() == null) {
                result.add(dept);
            }else {
                Department parent = deptMap.get(dept.getParentId());
                if (parent!= null) {
                    parent.getChildren().add(dept);
                }
            }
        }
        return result;
    }


}
